package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RequestMapping("/scope")
@RestController
public class BeanScopeController {
    @Autowired
    private ApplicationContext context;

    @Resource(name = "singleUser")
    private User singleUser;

    @Resource(name = "prototypeUser")
    private User prototypeUser;

    @Resource(name = "requestUser")
    private User requestUser;

    @Resource(name = "sessionUser")
    private User sessionUser;

    @Resource(name = "applicationUser")
    private User applicationUser;


    @RequestMapping("/single")
    public String single(){
        /**
         * 1. 从context获取对象
         * 2. 属性注入获取对象
         */
        User user = (User) context.getBean("singleUser");
        return "context获取的对象:"+user+",属性注入获取的对象:"+singleUser;

    }

    @RequestMapping("/prototype")
    public String prototype(){
        /**
         * 1. 从context获取对象
         * 2. 属性注入获取对象
         */
        User user = (User) context.getBean("prototypeUser");
        return "context获取的对象:"+user+",属性注入获取的对象:"+prototypeUser;
    }

    @RequestMapping("/request")
    public String request(){
        /**
         * 1. 从context获取对象
         * 2. 属性注入获取对象
         */
        User user = (User) context.getBean("requestUser");
        System.out.println(user.toString());
        System.out.println(user.getClass().getName() + "@" + Integer.toHexString(user.hashCode()));
        return "context获取的对象:"+user+",属性注入获取的对象:"+requestUser;
    }

    @RequestMapping("/session")
    public String session(){
        /**
         * 1. 从context获取对象
         * 2. 属性注入获取对象
         */
        User user = (User) context.getBean("sessionUser");
//        return "context获取的对象:"+System.identityHashCode(user)+",属性注入获取的对象:"+System.identityHashCode(sessionUser);
        return "context获取的对象:"+user+",属性注入获取的对象:"+sessionUser;
    }


    @RequestMapping("/application")
    public String application(){
        /**
         * 1. 从context获取对象
         * 2. 属性注入获取对象
         */
        User user = (User) context.getBean("applicationUser");
//        return "context获取的对象:"+System.identityHashCode(user)+",属性注入获取的对象:"+System.identityHashCode(sessionUser);
        return "context获取的对象:"+user+",属性注入获取的对象:"+applicationUser;
    }


}
